package metrics

import (
	"sync"
)

type SuccessRateAnalyser struct {
	sync.RWMutex
	name         string
	total        int
	successCount int
}

var DTSRegisterSuccessRateAnalyser = NewSuccessRateAnalyser("DTS-Register-Success-Rate-Analyser")
var DTSEnlistSuccessRateAnalyser = NewSuccessRateAnalyser("DTS-Enlist-Success-Rate-Analyser")
var DTSTryResultReportSuccessRateAnalyser = NewSuccessRateAnalyser("DTS-Try-Result-Report-Success-Rate-Analyser")
var DTSCallbackConfirmSuccessRateAnalyser = NewSuccessRateAnalyser("DTS-Callback-Confirm-Success-Rate-Analyser")
var DTSCallbackCancelSuccessRateAnalyser = NewSuccessRateAnalyser("DTS-Callback-Cancel-Success-Rate-Analyser")

func NewSuccessRateAnalyser(name string) *SuccessRateAnalyser {
	successRateAnalyser := &SuccessRateAnalyser{
		name: name,
	}

	return successRateAnalyser
}

func (t *SuccessRateAnalyser) IncreaseCount(isSuccess bool) {
	t.Lock()
	t.total++
	if isSuccess {
		t.successCount++
	}
	t.Unlock()
}

func (t *SuccessRateAnalyser) GetSuccessRateOfIntervalCountingTimeAndReset() float64 {
	t.Lock()
	defer func() {
		t.total = 0
		t.successCount = 0

		t.Unlock()
	}()

	if t.total > 0 {
		return 100.00 * float64(t.successCount) / float64(t.total)
	} else {
		return 100.00
	}
}
